package com.douya.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * 说明：AES加密工具类
 *
 * @Author 胡晨烨
 * @Date 2020/2/20
 */
@Slf4j
public class AESUtils {

    private static final String KEY_ALGORITHM = "AES/CBC/PKCS5Padding";


    public static String encrypt(String content, String secret, String iv) {
        return Base64.encodeBase64String(encrypt(content.getBytes(StandardCharsets.UTF_8), secret.getBytes(), iv.getBytes()));
    }

    public static String encryptHex(String content, String secret, String iv) {
        return Hex.encodeHexString(Objects.requireNonNull(encrypt(content.getBytes(StandardCharsets.UTF_8),
                secret.getBytes(), iv.getBytes())));
    }

    public static byte[] encrypt(byte[] data, byte[] secret, byte[] iv) {
        try {
            SecretKeySpec key = new SecretKeySpec(secret, "AES");
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(1, key, new IvParameterSpec(iv));
            return cipher.doFinal(data);
        } catch (Exception e) {
            log.error("Encrype error", e);
            return null;
        }
    }

    public static String decrypt(String content, String secret, String iv) {
        return StringUtils.toString(decrypt(Base64.decodeBase64(content), StringUtils.getBytes(secret), StringUtils.getBytes(iv)));
    }


    public static byte[] decrypt(byte[] content, byte[] secret, byte[] iv) {
        try {
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(2, new SecretKeySpec(secret, "AES"), new IvParameterSpec(iv));
            return cipher.doFinal(content);
        } catch (Exception e) {
            log.error("Decrypt error", e);
            return null;
        }
    }
}